<!doctype html>
<html class="theme-next use-motion theme-next-mist">
<head>
  
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="K8DCBviaoTBKVs28YBB7IBIbospQ9RVlgSh81RYMUhY" />


  <meta name="baidu-site-verification" content="tXr3ZTm3Hx" />



  <link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>


<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>

  <meta name="description" content="xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native." />


  <meta name="keywords" content="html2canvas,canvas2image,html2image," />


  <link rel="alternate" target="_blank" href="/atom.xml" title="xgfe" type="application/atom+xml" />


  <link rel="shorticon icon" type="image/x-icon" href="http://p0.meituan.net/xgfe/2db359f56ce13be30dedef160e0e57ce16958.ico?v=0.4.5.1" />

<meta name="description" content="如何将HTML保存成高清图片？本文带你一探究竟。">
<meta name="keywords" content="html2canvas,canvas2image,html2image">
<meta property="og:type" content="article">
<meta property="og:title" content="如何将html保存成图片">
<meta property="og:url" content="http://xgfe.github.io/2017/09/07/huanglifen/html2image/index.html">
<meta property="og:site_name" content="xgfe">
<meta property="og:description" content="如何将HTML保存成高清图片？本文带你一探究竟。">
<meta property="og:image" content="http://p0.meituan.net/xgfe/9a8e54d6457a682eb167d77fd1d2d2ef594412.png">
<meta property="og:updated_time" content="2017-09-21T09:33:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="如何将html保存成图片">
<meta name="twitter:description" content="如何将HTML保存成高清图片？本文带你一探究竟。">
<meta name="twitter:image" content="http://p0.meituan.net/xgfe/9a8e54d6457a682eb167d77fd1d2d2ef594412.png">


<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mist',
    sidebar: 'post'
  };
</script>

  <title> 如何将html保存成图片 | xgfe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  <div style="position: fixed; top: -9999px; left: -9999px;">
    <img src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe"/>
  </div>
  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  

  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?3601d4483819a5ab6ddabb0b6422a328";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><h1 class="site-meta">
  <span class="logo-line-before"><i></i></span>
  <a href="/" class="brand" rel="start">
      <span class="logo">
        <i class="icon-next-logo"></i>
      </span>
      <span class="site-title">xgfe</span>
  </a>
  <span class="logo-line-after"><i></i></span>
</h1>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon icon-next-home"></i> <br />
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            <i class="menu-item-icon icon-next-archives"></i> <br />
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            <i class="menu-item-icon icon-next-tags"></i> <br />
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-join">
          <a href="/join" rel="section">
            <i class="menu-item-icon icon-next-join"></i> <br />
            加入我们
          </a>
        </li>
      
      <!-- slide-links added by felix -->
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="http://xgfe.github.io/Basics/" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Basics
        </a>
      </li>
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="https://slides.com/xgfe" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Slides
        </a>
      </li>

      
      
    </ul>
  

  
    <div class="site-search">
      

    </div>
  

    <div class="site-search">
      <form class="site-search-form" id="gg-form" action="https://www.google.com/webhp" >
        <input type="text" name="q" id="gg-search-input" class="menu-search-input">
      </form>
    </div>
</nav>
 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content"> 

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">

      
      
        <h1 class="post-title" itemprop="name headline">
          
          
            
              如何将html保存成图片
            
          
        </h1>
      

      <div class="post-meta">
        <span class="post-time">
          发表于
          <time itemprop="dateCreated" datetime="2017-09-07T00:00:00+08:00" content="2017-09-07">
            2017-09-07
          </time>
        </span>

        
          <span class="post-category" >
            &nbsp; | &nbsp; 作者
            
              <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                <a href="/categories/huanglifen/" itemprop="url" rel="index">
                  <span itemprop="name">huanglifen</span>
                </a>
              </span>

              
              

            
          </span>
        

        
          
        

        <!-- tags 挪动位置 -->
        
          <span class="post-tags">
            &nbsp; | &nbsp;
            
              <a href="/tags/html2canvas/" rel="tag"><i class="icon-next-tags"></i>html2canvas</a>
            
              <a href="/tags/canvas2image/" rel="tag"><i class="icon-next-tags"></i>canvas2image</a>
            
              <a href="/tags/html2image/" rel="tag"><i class="icon-next-tags"></i>html2image</a>
            
          </span>
        
      </div>
    </header>

    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><p>如何将HTML保存成高清图片？本文带你一探究竟。<br><a id="more"></a></p>
<h2 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h2><p>现在流行于朋友圈分享的一些活动页，经常会玩这样的一个功能：将诸如测试之类的结果页保存成图片分享至朋友圈，以此来吸引用户参与，提高活动的pv和uv。</p>
<h2 id="如何做"><a href="#如何做" class="headerlink" title="如何做"></a>如何做</h2><p>一般来说有这两个技术步骤：</p>
<ul>
<li>html2canvas</li>
<li>canvas2image</li>
</ul>
<p>当需要连同html中跨域的图片一起转换时，需要增加一个base步骤：</p>
<ul>
<li>image proxy（因为canvas2image不支持跨域的图片, 本篇只是点到，不做展开）</li>
<li>html2canvas</li>
<li>canvas2image</li>
</ul>
<p>首先需要将html转成canvas， 再接着将canvas转为图片，至此，用户用手机自带的功能长按就可以保存，当然你也可以自己做长按保存的功能，canvas2image 提供了保存成图片的api。</p>
<h2 id="html2canvas"><a href="#html2canvas" class="headerlink" title="html2canvas"></a>html2canvas</h2><h3 id="如何转换的"><a href="#如何转换的" class="headerlink" title="如何转换的"></a>如何转换的</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">The script traverses through the DOM of the page it is loaded on. </div><div class="line">It gathers information on all the elements there, which it then uses to build a representation of the page. </div><div class="line">In other words, it does not actually take a screenshot of the page, </div><div class="line">but builds a representation of it based on the properties it reads from the DOM.</div><div class="line">As a result, it is only able to render correctly properties that it understands, </div><div class="line">meaning there are many CSS properties which do not work.</div></pre></td></tr></table></figure>
<p>翻译过来就是：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">通过脚本去遍历页面加载的DOM元素，收集所有元素的有关信息，然后用收集到的信息来构建页面的表示。</div><div class="line">换句话说，它实际上并不是页面的屏幕截图，而是基于从DOM读取的属性来构建页面的表示。</div><div class="line">因此，它只能够正确地呈现其理解的属性，这就意味着有许多CSS属性不起作用。</div></pre></td></tr></table></figure></p>
<h3 id="制约点"><a href="#制约点" class="headerlink" title="制约点"></a>制约点</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">All the images that the script uses need to reside under the same origin </div><div class="line">for it to be able to read them without the assistance of a proxy. </div><div class="line">Similarly, if you have other canvas elements on the page, which have been </div><div class="line">tainted with cross-origin content, they will become dirty and no longer readable by html2canvas.</div><div class="line">The script doesn&apos;t render plugin content such as Flash or Java applets.</div><div class="line">It doesn&apos;t render iframe content either.</div></pre></td></tr></table></figure>
<p>翻译过来就是：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">脚本使用的所有图像都必须位于相同的起源点，以便脚本不需要代理协助就可以读取它们的信息。</div><div class="line">类似地，如果页面上有其他canvas元素，这些元素已经被不是同源的内容所污染，就不能被html2canvas读取。</div><div class="line">简单来说就两点：</div><div class="line">- 不支持跨域</div><div class="line">- 不支持HTML中包含canvas</div></pre></td></tr></table></figure></p>
<p>参数说明</p>
<table>
<thead>
<tr>
<th>Name</th>
<th style="text-align:center">Type</th>
<th style="text-align:center">Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>allowTaint</td>
<td style="text-align:center">boolean</td>
<td style="text-align:center">false</td>
<td>是否允许图片跨域</td>
</tr>
<tr>
<td>background</td>
<td style="text-align:center">string</td>
<td style="text-align:center">#fff</td>
<td>画布背景颜色，如果DOM中未指定，值为透明</td>
</tr>
<tr>
<td>height</td>
<td style="text-align:center">number</td>
<td style="text-align:center">null</td>
<td>以像素为单位定义画布的高度。 如果为空，则按窗口的高度来渲染</td>
</tr>
<tr>
<td>width</td>
<td style="text-align:center">number</td>
<td style="text-align:center">null</td>
<td>以像素为单位定义画布的宽度。 如果为空，则按窗口的宽度来渲染</td>
</tr>
<tr>
<td>letterRendering</td>
<td style="text-align:center">boolean</td>
<td style="text-align:center">false</td>
<td>是否分别渲染每一个字符，必要时使用letter-spacing</td>
</tr>
<tr>
<td>logging</td>
<td style="text-align:center">boolean</td>
<td style="text-align:center">false</td>
<td>是否开启控制台日志</td>
</tr>
<tr>
<td>proxy</td>
<td style="text-align:center">string</td>
<td style="text-align:center">undefined</td>
<td>设置用于加载跨域图片的代理域名，如果为空，跨域的图片不会被加载</td>
</tr>
<tr>
<td>taintTest</td>
<td style="text-align:center">boolean</td>
<td style="text-align:center">true</td>
<td>设置是否在渲染前检测每张图片加载完</td>
</tr>
<tr>
<td>timeout</td>
<td style="text-align:center">number</td>
<td style="text-align:center">0</td>
<td>设置超时加载图片，毫秒为单位，设置为0则无超时</td>
</tr>
<tr>
<td>useCORS</td>
<td style="text-align:center">boolean</td>
<td style="text-align:center">false</td>
<td>是否在还原到代理服务器之前尝试将跨域的图像加载为CORS</td>
</tr>
<tr>
<td>scale</td>
<td style="text-align:center">number</td>
<td style="text-align:center">1</td>
<td>转换时放大的倍数，可以通过获取设备的像素密度来定义，也可以自定义</td>
</tr>
</tbody>
</table>
<h3 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h3><p>转换后的canvas会传递到回调函数中<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">html2canvas(element, &#123;</div><div class="line">    <span class="attr">onrendered</span>: <span class="function"><span class="keyword">function</span>(<span class="params">canvas</span>) </span>&#123;</div><div class="line">        <span class="comment">// canvas is the final rendered &lt;canvas&gt; element</span></div><div class="line">    &#125;</div><div class="line">&#125;);</div><div class="line"></div><div class="line">或者</div><div class="line"></div><div class="line">html2canvas(element, options).then(<span class="function"><span class="keyword">function</span> (<span class="params">canvas</span>) </span>&#123;</div><div class="line">    <span class="comment">// canvas is the final rendered &lt;canvas&gt; element</span></div><div class="line">&#125;);</div></pre></td></tr></table></figure></p>
<p>想要了解更多信息，请前往官网地址：<a href="http://html2canvas.hertzen.com/" target="_blank" rel="external">http://html2canvas.hertzen.com/</a></p>
<h2 id="canvas2image"><a href="#canvas2image" class="headerlink" title="canvas2image"></a>canvas2image</h2><p>你可以使用的API:<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">Canvas2Image.saveAsImage(canvasObj, width, height, type)</div><div class="line">Canvas2Image.saveAsPNG(canvasObj, width, height)</div><div class="line">Canvas2Image.saveAsJPEG(canvasObj, width, height)</div><div class="line">Canvas2Image.saveAsGIF(canvasObj, width, height)</div><div class="line">Canvas2Image.saveAsBMP(canvasObj, width, height)</div><div class="line"></div><div class="line">Canvas2Image.convertToImage(canvasObj, width, height, type)</div><div class="line">Canvas2Image.convertToPNG(canvasObj, width, height)</div><div class="line">Canvas2Image.convertToJPEG(canvasObj, width, height)</div><div class="line">Canvas2Image.convertToGIF(canvasObj, width, height)</div><div class="line">Canvas2Image.convertToBMP(canvasObj, width, height)</div></pre></td></tr></table></figure></p>
<h2 id="举个栗子"><a href="#举个栗子" class="headerlink" title="举个栗子"></a>举个栗子</h2><p>html：<br><figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"main"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"html-source width-6 fl"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"img/timg.jpeg"</span> <span class="attr">class</span>=<span class="string">"width-6"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">p</span>&gt;</span>图片描述文字<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"option-content width-4 fl"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">"button start-to-do"</span>&gt;</span>转换成图片<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">"button"</span>&gt;</span>下载图片<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"png-content width-6 fl"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>核心js：为获得高清的图片，先以N倍的尺寸转换成canvas, 再1：1转换成png, 最后通过样式去控制最后生成的图片展示尺寸。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> me = <span class="keyword">this</span>;</div><div class="line"><span class="keyword">var</span> sourceContent = me.$el.$htmlSource;</div><div class="line"><span class="keyword">var</span> width = sourceContent.width();</div><div class="line"><span class="keyword">var</span> height = sourceContent.height();</div><div class="line"><span class="keyword">var</span> offsetTop = sourceContent.offset().top;</div><div class="line"><span class="keyword">var</span> offsetLeft = sourceContent.offset().left;</div><div class="line"><span class="keyword">var</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">"canvas"</span>);</div><div class="line"><span class="keyword">var</span> canvas2D = canvas.getContext(<span class="string">"2d"</span>);</div><div class="line"></div><div class="line"><span class="comment">// 不能小于1，否则图片不完整，通过获取设备的像素密度不能统一得到清晰的图片，建议写固定值</span></div><div class="line"><span class="keyword">var</span> scale = N;</div><div class="line">canvas.width = (width + offsetLeft) * scale;</div><div class="line">canvas.height = (height + offsetTop) * scale;</div><div class="line">canvas2D.scale(scale, scale);</div><div class="line">canvas2D.font = <span class="string">"Microsoft YaHei"</span>;</div><div class="line"><span class="keyword">var</span> options = &#123;</div><div class="line"></div><div class="line">    <span class="comment">//检测每张图片都已经加载完成</span></div><div class="line">    tainttest:<span class="literal">true</span>,</div><div class="line">    <span class="attr">canvas</span>: canvas,</div><div class="line">    <span class="attr">scale</span>: scale,</div><div class="line"></div><div class="line">    <span class="comment">//dom 放大的宽度，放大倍数和清晰度在一定范围内成正相关</span></div><div class="line">    width: width + offsetLeft,</div><div class="line"></div><div class="line">    <span class="comment">// 开启日志，可以方便调试</span></div><div class="line">    logging: <span class="literal">true</span>,</div><div class="line"></div><div class="line">    <span class="comment">//dom 放大的宽度，放大倍数和清晰度在一定范围内成正相关</span></div><div class="line">    height: height + offsetTop</div><div class="line">&#125;;</div><div class="line">html2canvas(sourceContent, options).then(<span class="function"><span class="keyword">function</span> (<span class="params">canvas</span>) </span>&#123;</div><div class="line">    <span class="keyword">var</span> img = <span class="built_in">window</span>.Canvas2Image.convertToPNG(canvas, width * scale, height * scale);</div><div class="line">    me.$el.$pngContent.append(img);</div><div class="line"></div><div class="line">    <span class="comment">// 将图片恢复到原始大小</span></div><div class="line">    me.$el.$pngContent.find(<span class="string">'img'</span>).css(&#123;</div><div class="line">        <span class="attr">width</span>: width,</div><div class="line">        <span class="attr">height</span>: height</div><div class="line">    &#125;);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>下面是不同的倍数N，生成的不同清晰度的图片：<br><img src="http://p0.meituan.net/xgfe/9a8e54d6457a682eb167d77fd1d2d2ef594412.png" alt="效果图（倍数N: 1~3.5）"></p>
<p>之前做过一次项目，N设为3 可以满足多种主流手机的高清图片要求。</p>
<h3 id="附完整源代码"><a href="#附完整源代码" class="headerlink" title="附完整源代码"></a>附完整源代码</h3><p>需要说明的是： 页面需要运行于服务器中转换才能生效。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">content</span>=<span class="string">"width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"</span> <span class="attr">name</span>=<span class="string">"viewport"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="javascript"></span></div><div class="line">        (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">            <span class="keyword">var</span> win = <span class="built_in">window</span>, html = <span class="built_in">document</span>.documentElement;</div><div class="line">            <span class="function"><span class="keyword">function</span> <span class="title">setRem</span>(<span class="params"></span>) </span>&#123;</div><div class="line">                <span class="keyword">var</span> width = html.getBoundingClientRect().width;</div><div class="line">                width = (width == <span class="number">980</span>) ? <span class="number">360</span> : width;</div><div class="line">                <span class="keyword">var</span> rem = width / <span class="number">20</span>;</div><div class="line">                win.rem = rem;</div><div class="line">                html.style.fontSize = rem + <span class="string">'px'</span>;</div><div class="line">            &#125;</div><div class="line">            setRem();</div><div class="line">        &#125;)();</div><div class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">style</span> <span class="attr">type</span>=<span class="string">"text/css"</span>&gt;</span><span class="undefined"></span></div><div class="line">        * &#123;</div><div class="line">            padding: 0;</div><div class="line">            margin: 0;</div><div class="line">        &#125;</div><div class="line">        .main &#123;</div><div class="line">            padding: 0.2rem;</div><div class="line">            background: #fafafa;</div><div class="line">            overflow: auto;</div><div class="line">        &#125;</div><div class="line">        .width-2 &#123;</div><div class="line">            width: 2rem;</div><div class="line">        &#125;</div><div class="line">        .fl &#123;</div><div class="line">            float: left;</div><div class="line">        &#125;</div><div class="line">        .html-source &#123;</div><div class="line">            height: 10rem;</div><div class="line">        &#125;</div><div class="line">        .html-text &#123;</div><div class="line">            font-size: 0.2rem;</div><div class="line">        &#125;</div><div class="line">        .png-content &#123;</div><div class="line">            height: 20rem;</div><div class="line">        &#125;</div><div class="line">        .png-content img &#123;</div><div class="line">            border: 0;</div><div class="line">            margin: 0 0.2rem;</div><div class="line">        &#125;</div><div class="line">        .button &#123;</div><div class="line">            color: #fff;</div><div class="line">            background-color: #23b7e5;</div><div class="line">            border-color: #23b7e5;</div><div class="line">            font-weight: 500;</div><div class="line">            border-radius: 0.1rem;</div><div class="line">            outline: 0;</div><div class="line">            font-size: 0.2rem;</div><div class="line">            margin: 0 0.5rem;</div><div class="line">        &#125;</div><div class="line">    <span class="tag">&lt;/<span class="name">style</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"main"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"html-source width-2 fl"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"img/timg.jpeg"</span> <span class="attr">class</span>=<span class="string">"width-2"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"html-text"</span>&gt;</span>图片描述文字<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"option-content fl"</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">"button start-to-do"</span>&gt;</span>转换<span class="tag">&lt;/<span class="name">button</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"png-content"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"js/jquery-3.2.1.min.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"js/html2canvas.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"js/canvas2image.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="javascript"></span></div><div class="line">    <span class="keyword">var</span> page = &#123;</div><div class="line">        <span class="attr">init</span>: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">            <span class="keyword">this</span>.initDom();</div><div class="line">            <span class="keyword">this</span>.initEvent();</div><div class="line">        &#125;,</div><div class="line">        <span class="attr">initDom</span>: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">            <span class="keyword">this</span>.$el = &#123;&#125;;</div><div class="line">            <span class="keyword">this</span>.$el.$startBtn = $(<span class="string">'.start-to-do'</span>);</div><div class="line">            <span class="keyword">this</span>.$el.$htmlSource = $(<span class="string">'.html-source'</span>);</div><div class="line">            <span class="keyword">this</span>.$el.$pngContent = $(<span class="string">'.png-content'</span>);</div><div class="line">        &#125;,</div><div class="line">        <span class="attr">initEvent</span>: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">            <span class="keyword">var</span> me = <span class="keyword">this</span>;</div><div class="line">            <span class="keyword">this</span>.$el.$startBtn.on(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">                <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">2</span>; i &lt; <span class="number">8</span>; i++) &#123;</div><div class="line">                    me.initSavePng(i * <span class="number">0.5</span>);</div><div class="line">                &#125;</div><div class="line">            &#125;);</div><div class="line">        &#125;,</div><div class="line">        <span class="attr">initSavePng</span>: <span class="function"><span class="keyword">function</span>(<span class="params">N</span>) </span>&#123;</div><div class="line">            <span class="keyword">var</span> me = <span class="keyword">this</span>;</div><div class="line">            <span class="keyword">var</span> sourceContent = me.$el.$htmlSource;</div><div class="line">            <span class="keyword">var</span> width = sourceContent.width();</div><div class="line">            <span class="keyword">var</span> height = sourceContent.height();</div><div class="line">            <span class="keyword">var</span> offsetTop = sourceContent.offset().top;</div><div class="line">            <span class="keyword">var</span> offsetLeft = sourceContent.offset().left;</div><div class="line">            <span class="keyword">var</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">"canvas"</span>);</div><div class="line">            <span class="keyword">var</span> canvas2D = canvas.getContext(<span class="string">"2d"</span>);</div><div class="line"></div><div class="line">            <span class="comment">// 不能小于1，否则图片不完整</span></div><div class="line">            <span class="keyword">var</span> scale = N;</div><div class="line">            canvas.width = (width + offsetLeft) * scale;</div><div class="line">            canvas.height = (height + offsetTop) * scale;</div><div class="line">            canvas2D.scale(scale, scale);</div><div class="line">            canvas2D.font = <span class="string">"Microsoft YaHei"</span>;</div><div class="line">            <span class="keyword">var</span> options = &#123;</div><div class="line"></div><div class="line">                <span class="comment">//检测每张图片都已经加载完成</span></div><div class="line">                tainttest:<span class="literal">true</span>,</div><div class="line">                <span class="attr">canvas</span>: canvas,</div><div class="line">                <span class="attr">scale</span>: scale,</div><div class="line"></div><div class="line">                <span class="comment">//dom 放大的宽度，放大倍数和清晰度在一定范围内成正相关</span></div><div class="line">                width: width + offsetLeft,</div><div class="line"></div><div class="line">                <span class="comment">// 开启日志，可以方便调试</span></div><div class="line">                logging: <span class="literal">true</span>,</div><div class="line"></div><div class="line">                <span class="comment">//dom 放大的宽度，放大倍数和清晰度在一定范围内成正相关</span></div><div class="line">                height: height + offsetTop</div><div class="line">            &#125;;</div><div class="line">            html2canvas(sourceContent, options).then(<span class="function"><span class="keyword">function</span> (<span class="params">canvas</span>) </span>&#123;</div><div class="line">                <span class="keyword">var</span> img = <span class="built_in">window</span>.Canvas2Image.convertToPNG(canvas, width * scale, height * scale);</div><div class="line">                me.$el.$pngContent.append(img);</div><div class="line"></div><div class="line">                <span class="comment">// 将图片恢复到原始大小</span></div><div class="line">                me.$el.$pngContent.find(<span class="string">'img'</span>).css(&#123;</div><div class="line">                    <span class="attr">width</span>: width,</div><div class="line">                    <span class="attr">height</span>: height</div><div class="line">                &#125;);</div><div class="line">            &#125;);</div><div class="line">        &#125;</div><div class="line">    &#125;;</div><div class="line"></div><div class="line">    page.init();</div><div class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></div></pre></td></tr></table></figure>
<p>完整示例代码git地址：<a href="https://github.com/huanlifen/html2image" target="_blank" rel="external">https://github.com/huanlifen/html2image</a></p>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><p>1.<a href="https://github.com/niklasvh/html2canvas" target="_blank" rel="external">原版html2canvas</a><br>2.<a href="https://github.com/omwteam/html2canvas" target="_blank" rel="external">优化版html2canvas 0.5.0-beta4</a></p>
</span>
      
    </div>

    <footer class="post-footer">

      
        <div class="post-nav">
          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/07/felix/html-parsing-and-resources-load/" rel="prev">HTML解析和资源加载</a>
            
          </div>

          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/28/DaisyXL/ES6/" rel="next">ES6项目构建</a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

 </div>

        

        
          <div class="comments" id="comments">
            <div id="SOHUCS" sid="" ></div>
          </div>
        
      </div>

      
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <a href="https://github.com/xgfe" target="_blank"><img class="site-author-image" src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe" itemprop="image"/></a>
          <p class="site-author-name" itemprop="name">xgfe</p>
        </div>
        <p class="site-description motion-element" itemprop="description">xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native.</p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">89</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            
              <span class="site-state-item-count">37</span>
              <span class="site-state-item-name">作者</span>
              
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">131</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" target="_blank" rel="alternate">
              <i class="menu-item-icon icon-next-feed"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xgfe" target="_blank">GitHub</a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator"></div>
          <div class="post-toc">
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用场景"><span class="nav-number">1.</span> <span class="nav-text">使用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何做"><span class="nav-number">2.</span> <span class="nav-text">如何做</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#html2canvas"><span class="nav-number">3.</span> <span class="nav-text">html2canvas</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#如何转换的"><span class="nav-number">3.1.</span> <span class="nav-text">如何转换的</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#制约点"><span class="nav-number">3.2.</span> <span class="nav-text">制约点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用"><span class="nav-number">3.3.</span> <span class="nav-text">使用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#canvas2image"><span class="nav-number">4.</span> <span class="nav-text">canvas2image</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#举个栗子"><span class="nav-number">5.</span> <span class="nav-text">举个栗子</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#附完整源代码"><span class="nav-number">5.1.</span> <span class="nav-text">附完整源代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考资料"><span class="nav-number">6.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator"></div>
        </section>
      

    </div>
  </aside>


    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner"> <div class="copyright" >
  
  &copy; &nbsp; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xgfe</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" target="_blank" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


 </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  
  
    <script type="text/javascript"> 
(function(){ 
var appid = 'cysWiXvkm'; 
var conf = 'prod_fc970dbe85103c7a79b2c4f3dc7fb190'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="http://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("http://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    

  


  
  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
  

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>




  <script type="text/javascript" src="/js/nav-toggle.js?v=0.4.5.1"></script>
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.1" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 0.4 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    var $tocContent = $('.post-toc-content');
    if (isDesktop() && CONFIG.sidebar === 'post') {
      if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
        displaySidebar();
      }
    }
  });
</script>



  <script type="text/javascript">
    $(document).ready(function () {
      if (CONFIG.sidebar === 'always') {
        displaySidebar();
      }
      if (isMobile()) {
        FastClick.attach(document.body);
      }
    });
  </script>

  

  
  

  
  <script type="text/javascript" src="/js/lazyload.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#posts").find('img').lazyload({
        placeholder: "/images/loading.gif",
        effect: "fadeIn"
      });
    });
  </script>

  <!-- google search, added by felix -->
  <script>
      $('#gg-form').on('submit', function(e) {
        var keyword = $.trim($(this).find('#gg-search-input').val());
        if (keyword) {
          location.href = 'https://www.google.com.hk/?gfe_rd=cr&ei=hXw8VpjtHuLC8AeSuIjQAg&gws_rd=ssl#safe=strict&q='+encodeURIComponent(keyword)+'+site:xgfe.github.io';
        }
        return false;
      });
  </script>
  <!-- baidu 站长自动推送 -->
  <script>
  (function(){
      var bp = document.createElement('script');
      bp.src = '//push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</body>
</html>
